package com.kfm.usermanagement.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GenderHandler extends BaseTypeHandler<String> {
    /**
     * 往数据库插入数据的时候通过这个方法进行转换
     * @param ps
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if ("男".equals(parameter)) {
            ps.setInt(i, 1);
        } else {
            ps.setInt(i, 0);
        }
    }

    /**
     * 查询出来数据之后封装到实体类对象的时候调用该方法
     * @param rs
     *          the rs
     * @param columnName
     *          Column name, when configuration <code>useColumnLabel</code> is <code>false</code>
     *
     * @return
     * @throws SQLException
     */
    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return getGender(rs.getInt(columnName));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return getGender(rs.getInt(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return getGender(cs.getInt(columnIndex));
    }

    private String getGender(int gender) {
        return gender == 1 ? "男" : "女";
    }
}
